//
//  HomeTableController.swift
//  weibobbaj
//
//  Created by Tiffany宝 on 16/4/16.
//  Copyright © 2016年 Tiffany. All rights reserved.
//

import UIKit

class HomeTableController: VisiableTableController {
    
    let HomeTableCellID = "HomeTableCellID"
    
    let statusViewModel: StatusViewModel = StatusViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        if !userLogin {
            
            vbView.setupVisibleInfo(nil, title: nil)
        }
        
        setupUI()
        
        loadData()
        
    }
    
    private func setupUI(){
        
        //注册cell swift中类要写self -- UITableViewCell.self , OC中为 [UITableViewCell class]
        tableView.registerClass(StatusCell.self, forCellReuseIdentifier: HomeTableCellID)
        
//        自动计算行高,预估行高
        tableView.rowHeight = UITableViewAutomaticDimension
        
        tableView.estimatedRowHeight = 200
        
//        tableView.rowHeight = 120
        
        //去除分割线
        tableView.separatorStyle = .None
        
        //设置背景色
        tableView.backgroundColor = UIColor(white: 237/255, alpha: 1)
        
        //把上拉View添加到 tableFooterView 上
        tableView.tableFooterView = pullupView
        
        //添加自定义刷新控件
        tableView.addSubview(XhRefreshControl)
        
        //初始化下拉刷新控件 -- 系统刷新控件
//        self.refreshControl =  UIRefreshControl()
        
        //添加刷新控件的点击监听事件
        XhRefreshControl.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
//        XhRefreshControl.addTarget(self, action: "haha", forControlEvents: UIControlEvents.ValueChanged)
        
        //添加下拉提示label
        //目的是添加到导航栏的后面, tableViewController 的前面,并且不跟随 tableViewController 的滚动而滚动 API
        self.navigationController?.view.insertSubview(PullDownTip, belowSubview: self.navigationController!.navigationBar)
    }
    
    
    // MARK: - 测试刷新事件
    func haha() {
        
        print("哈哈")
        
        //结束刷新
        self.performSelector("endRefresh", withObject: self, afterDelay: 3)
//        self.endRefresh()
    }
    
    @objc private func loadData(){
        
        statusViewModel.loadStatus(pullupView.isAnimating()) { (isSuccess,count) -> () in
            
            if isSuccess{
                
                //刷新数据
                self.tableView.reloadData()
                
//                print("成功加载----\(count)")
                
            }else{
                
                print("数据请求错误")
            }
            
            //结束刷新
            self.endRefresh()
            
            
            //调用下拉提示tip方法
            self.showPullDownTip(count)
        }
        
    }
    
    // MARK: - 下拉提示tip方法
    func showPullDownTip(count: Int){
        
        //设置起始位置
        let tipY = CGRectGetMaxY(self.navigationController!.navigationBar.frame) - self.PullDownTip.bounds.height
        self.PullDownTip.frame.origin.y = tipY

        if self.PullDownTip.hidden == false{
            return
        }
        self.PullDownTip.hidden = false
        self.PullDownTip.text = count > 0 ? "成功加载数据\(count)条" : "没有新的微博数据"
        UIView.animateWithDuration(1, animations: { () -> Void in
            
            self.PullDownTip.frame.origin.y = CGRectGetMaxY(self.navigationController!.navigationBar.frame)
            //                    + self.PullDownTip.bounds.height
            }, completion: { (_) -> Void in
                
                UIView.animateWithDuration(1, delay: 1, options: [], animations: { () -> Void in
                    
                    self.PullDownTip.frame.origin.y = tipY
                    }, completion: { (_) -> Void in
                        
//                        print("-----")
                        self.PullDownTip.hidden = true
                })
        })
    }
    
    // MARK: - 结束刷新
    func endRefresh(){
        
        //数据加载完成,菊花停止
        self.pullupView.stopAnimating()
        //结束下拉刷新
//        self.refreshControl?.endRefreshing()
        XhRefreshControl.endRefreshing()
        
    }
    
     //懒加载上拉View
    private lazy var pullupView: UIActivityIndicatorView = {
        
       let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        
//        indicator.color = UIColor.whiteColor()
        
        //测试用
//        indicator.hidesWhenStopped = false
        
        return indicator
        
    }()
    
    //懒加载自定义刷新控件
    private lazy var XhRefreshControl: XHRefreshControl = XHRefreshControl()
    
    //懒加载下拉刷新提示label
    private lazy var PullDownTip: UILabel = {
        
       let tip = UILabel(textFont: 12, textColor: UIColor.whiteColor())
        tip.backgroundColor = UIColor.darkGrayColor()
        //设置tip的大小
        tip.frame = CGRect(x: 0, y: 0, width: SCREENW, height: 35)
//        tip.frame.size = CGSize(width: SCREENW, height: 35)
        tip.hidden = true
        
        tip.textAlignment = .Center
        
        return tip
    }()
    
//    //记录一下
//    var statusArray: [StatusModel]?{
//        
//        didSet{
//            //拿到数据就刷新界面
//            tableView.reloadData()
//        }
//    }
    
//    //加载首页的数据
//    private func loadStatus(){
//        
//        let url = "https://api.weibo.com/2/statuses/home_timeline.json"
//        
//        //account? 所以直接这样写会报错
////        let parameters = ["access_token":UserAccountViewModel.sharedViewModel.account?.access_token]
//        
//        guard let account = UserAccountViewModel.sharedViewModel.account?.access_token else{
//            
//            return
//        }
//        
//        let parameters = ["access_token":account]
//        NetworkTools.sharedTools.request( urlString: url, parameters: parameters) { (responseObject, error) -> Void in
//            
//            if error != nil{
//                
//                print(error)
//                return
//            }
//            print(responseObject)
//            
//            guard let dic = responseObject as? [String : AnyObject] else{
//                
//                print("字典格式错误")
//                return
//            }
//            
//            guard let arr = dic["statuses"] as? [[String : AnyObject]] else{
//                
//                return
//            }
//            
//            //定义一个可变数组
//            var statusArr = [StatusModel]()
//            
//            //遍历数组
//            for value in arr{
//                
//                //字典转模型
//                let model = StatusModel(dic: value)
//                statusArr.append(model)
//            }
//            
//            print(statusArr)
//            self.statusArray = statusArr
//        }
//    }
}

extension HomeTableController{
    
    // 将要加载某个cell的时候，会去掉用这个方法
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if indexPath.row == statusViewModel.cellArray!.count - 1 && !pullupView.isAnimating() {
            
            print("将要加载最后一个cell")
            
            //菊花转
            pullupView.startAnimating()
            
            //加载数据
            loadData()
        }
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return statusViewModel.cellArray?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        //IOS7.0之后用的方法,用这个方法：系统会去缓存中取，如果没有取到，就帮我们创建一个并返回。但是前提就是我们必须注册
        let cell = tableView.dequeueReusableCellWithIdentifier(HomeTableCellID, forIndexPath: indexPath) as? StatusCell
        
//        cell.textLabel?.text = statusViewModel.cellArray![indexPath.row].text
        
        cell?.statusViewModel = statusViewModel.cellArray![indexPath.row]
        
        // 以下写法是 iOS 7 之前的写法。
        //        var cell = tableView.dequeueReusableCellWithIdentifier("cell")
        //        if cell == nil {
        //            cell = HMStatusCell()
        //        }
        //        return cell!

        return cell!
    }
}










